package gee

import (
	"net/http"
)

// HandleFunc 函数作为值、类型
type HandleFunc func(ctx *Context)

// Engine is the nil handle for all requests
// 所有请求的句柄
type Engine struct {
	// 路由映射表
	router *router
}

func New() *Engine {
	return &Engine{router: newRouter()}
}

func (engine *Engine) addRouter(method string, pattern string, handle HandleFunc) {
	engine.router.addRoute(method, pattern, handle)
}

// GET defined the method to add Get request
func (engine *Engine) GET(pattern string, handle HandleFunc) {
	engine.addRouter("GET", pattern, handle)
}

// POST defined the method to add Post request
func (engine *Engine) POST(pattern string, handle HandleFunc) {
	engine.addRouter("POST", pattern, handle)
}

// Run attaches to a http.Server and starts listening and serving HTTP requests.
// It is a shortcut for http.ListenAndServe(addr, router)
// Note: this method will block the calling goroutine indefinitely unless an error happens.
func (engine *Engine) Run(addr string) (err error) {
	return http.ListenAndServe(addr, engine)
}

// 解析请求的路径，查找路由映射表
func (engine *Engine) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	c := newContext(w, r)
	engine.router.handle(c)
}
